import pymysql
from pymysql import cursors

from Config.db_config import ticketDb


class DbUtil:

    # 获取数据库的连接对象和cursor对象
    @staticmethod
    def openDb(host, port, user, password, db):
        # 获取连接对象
        connObj = pymysql.connect(host=ticketDb['host'], port=ticketDb['port'], user=ticketDb['user'],
                                  password=ticketDb['passwd'], db=ticketDb['db'], charset="utf8")
        # 获取cursor对象
        cursor = connObj.cursor(cursors.DictCursor)
        return connObj, cursor

    @staticmethod
    def readAll(sql, cursor):
        cursor.execute(sql)
        record = cursor.fetchall()
        return record

    @staticmethod
    def readOne(sql, cursor):
        cursor.execute(sql)
        record = cursor.fetchone()
        return record

    @staticmethod
    def writeDb(sql, cursor):
        # result ： sql执行后 对数据库的数据记录影响的行数
        result = cursor.execute(sql)
        return result

    @staticmethod
    def release(cursor, connObj):
        if cursor != None:
            cursor.close()
        if connObj != None:
            connObj.close()


if __name__ == '__main__':
    connObj, cursor = DbUtil.openDb(host="127.0.0.1", port=3306, user="root", password="123456"
                                    , db="ticketonline")
    print(connObj)
    sql = "select * from tb_actor where actor_id = 126"
    result = DbUtil.readOne(sql, cursor)
    print(result)

    DbUtil.release(cursor, connObj)
